﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyDude : Enemy
{

	#region 成员变量
	public EnemyDudeMoveType moveType;
	public Transform tr1, tr2;    // 在两个位置之前来回走动
	Vector3 t1, t2;

	public Transform dieTarget;

	float moveSpeed;
	private float tmpSpeed;
	public bool IsDie => ani.GetBool("IsDie");

	#endregion

	protected override void Start() {
		base.Start();
		SetIniAttributes(moveType);
	}

	public override void OnTriggerEnter2D(Collider2D other) {
		base.OnTriggerEnter2D(other);
		if (other.transform == dieTarget && moveType == EnemyDudeMoveType.AlwaysRun) {
			Destroy(this.gameObject);   // 撞墙而死, 不计入Player打死数量
		}
	}


	#region 重写暂停与继续
	public override void OnPauseAni() {
		base.OnPauseAni();
		moveSpeed = 0;
	}

	public override void OnContinueAni() {
		base.OnContinueAni();
		moveSpeed = tmpSpeed;
	}
	#endregion


	/// <summary>
	/// 怪物属性初始化
	/// </summary>
	/// <param name="moveType"></param>
	public void SetIniAttributes(EnemyDudeMoveType moveType) {
		// base.SetIniAttributes(hp, price, attack, type);

		if (moveType == EnemyDudeMoveType.AlwaysRun) {
			tmpSpeed = moveSpeed = 8;
			StartCoroutine(AlwaysRun(false));
			base.SetIniAttributes(1, 1, 1, EnemyType.EnemyDude);

		} else if (moveType == EnemyDudeMoveType.LeftAndRightWalk) {
			tmpSpeed = moveSpeed = 2;
			StartCoroutine(LeftAndRightWalk());
			base.SetIniAttributes(6, 3, 2, EnemyType.EnemyDude);
			transform.localScale *= 1.2f;
		}

	}

	#region 怪物移动的方式
	private IEnumerator AlwaysRun(bool isRight) {
		// int loop = 36;
		SetEnemyState(EnemyState.Run, true);
		int dir = isRight ? -1 : 1;
		while (true) {
			transform.Translate(Vector3.left * dir * Time.deltaTime * moveSpeed);
			yield return null;

			if (IsDie) {    // 被打死
				SetEnemyState(EnemyState.Die, true);
				yield break;
			}
		}
	}


	private IEnumerator LeftAndRightWalk() {
		SetEnemyState(EnemyState.Walk, true);

		t1 = tr1.position;
		t2 = tr2.position;
		Vector3 scale = transform.localScale;

		int dir = 1;
		int cnt = 0;
		while (true) {

			if (allowMove) transform.Translate(Vector3.left * dir * Time.deltaTime * moveSpeed);

			Vector3 v1 = t1 - transform.position;
			Vector3 v2 = t2 - transform.position;
			if (Vector3.Angle(v1, v2) <= 30) {    // 向量夹角小于30度, 需要改变方向
				dir = Vector3.Distance(Vector3.zero, v1) < Vector3.Distance(Vector3.zero, v2) ? 1 : -1;
				if (cnt == 0) {
					transform.localScale = new Vector3(dir * scale.x, scale.y, scale.z);
					cnt++;
				}
			} else {
				cnt = 0;
			}
			yield return null;
		}

	}
	#endregion


}
public enum EnemyDudeMoveType
{
	AlwaysRun,      // 周期性生成怪物朝一个方向奔跑直到消失在视野中或被打死
	LeftAndRightWalk,   // 在一个区域左右来回走动
}

